package cn.stylefeng.guns.modular.time.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.stylefeng.guns.modular.time.entity.Note;
import cn.stylefeng.guns.modular.time.mapper.NoteMapper;
import cn.stylefeng.guns.modular.time.model.request.NoteRequest;
import cn.stylefeng.guns.modular.time.service.NoteService;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements NoteService {

    @Override
    public PageResult<Note> findPage(NoteRequest request) {
        LambdaQueryWrapper<Note> qw = new LambdaQueryWrapper<>();
        qw.eq(Note::getDelFlag, "N")
          .eq(Note::getUserId, LoginContext.me().getLoginUser().getUserId())
          .orderByDesc(Note::getCreateTime);
        Page<Note> page = this.page(new Page<>(request.getPageNo(), request.getPageSize()), qw);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public void add(NoteRequest request) {
        Note n = new Note();
        n.setNoteId(null);
        n.setUserId(LoginContext.me().getLoginUser().getUserId());
        n.setTitle(request.getTitle());
        n.setContent(request.getContent());
        n.setCategory(request.getCategory());
        n.setDelFlag("N");
        n.setCreateTime(new Date());
        this.save(n);
    }

    @Override
    public void edit(NoteRequest request) {
        Note n = this.getById(request.getNoteId());
        if (n != null) {
            n.setTitle(request.getTitle());
            n.setContent(request.getContent());
            n.setCategory(request.getCategory());
            n.setUpdateTime(new Date());
            this.updateById(n);
        }
    }

    @Override
    public void delete(NoteRequest request) {
        this.removeById(request.getNoteId());
    }
}

